package com.device_manager.service.impl;

import com.device_manager.dto.ReturnRecordDTO;
import com.device_manager.entity.Box;
import com.device_manager.entity.Device;
import com.device_manager.entity.ReturnRecord;
import com.device_manager.mapper.ReturnMapper;
import com.device_manager.result.Result;
import com.device_manager.service.ReturnService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReturnServiceImpl implements ReturnService {
    @Autowired
    private ReturnMapper returnPersonMapper;
    @Override
    @Transactional
    public Result<String> addReturn(ReturnRecordDTO returnRecordDTO) {
        try {
            //逻辑需要修改
            //1.判断设备号是否入库
            List<String> returnedINDevices = new ArrayList<>();
            if (returnRecordDTO.getReturnDeciceList() != null && !returnRecordDTO.getReturnDeciceList().isEmpty()){
            for (ReturnRecordDTO.ReturnDevice deviceDTO : returnRecordDTO.getReturnDeciceList()) {
                //如果设备号未入库，则将该设备号记录下来
                if (returnPersonMapper.selectINDeviceMac(deviceDTO.getDeviceMac())) {
                    log.info(String.valueOf(deviceDTO.getDeviceMac()));
                }else
                    returnedINDevices.add(deviceDTO.getDeviceMac());
                }
            }
            //2.判断箱子号是否入库
            List<String> returnedINBoxes = new ArrayList<>();
            if (returnRecordDTO.getReturnBoxList()!= null && !returnRecordDTO.getReturnBoxList().isEmpty()) {
                for (ReturnRecordDTO.ReturnBox returnBox : returnRecordDTO.getReturnBoxList()) {
                    if (returnPersonMapper.selectINBoxNumber(returnBox.getBoxNumber())){
                        log.info(String.valueOf(returnBox.getBoxNumber()));
                    }else
                        returnedINBoxes.add(returnBox.getBoxNumber());

                }
            }
            // 3. 如果有设备、箱子未入库,返回未入库列表
            if (!returnedINDevices.isEmpty() || !returnedINBoxes.isEmpty()) {
                StringBuilder errorMsg = new StringBuilder("退货失败: ");

                if (!returnedINDevices.isEmpty()) {
                    errorMsg.append("以下设备未出库: ").append(String.join(", ", returnedINDevices));
                    log.error(String.valueOf(errorMsg));
                }

                if (!returnedINBoxes.isEmpty()) {
                    if (!returnedINDevices.isEmpty()) errorMsg.append("; ");
                    errorMsg.append("以下箱子未出库: ").append(String.join(", ", returnedINBoxes));
                    log.error(String.valueOf(errorMsg));
                }
                return Result.error(errorMsg.toString());
            }
            //1.判断退货设备号的is_returned是否为1，如果为1，则提示设备已退货
            List<String> returnedDevices = new ArrayList<>();
            if (returnRecordDTO.getReturnDeciceList() != null && !returnRecordDTO.getReturnDeciceList().isEmpty()) {
                for (ReturnRecordDTO.ReturnDevice returnDevice : returnRecordDTO.getReturnDeciceList()) {
                    String IsReturned = returnPersonMapper.selectDeviceMac(returnDevice.getDeviceMac());
                    if ("1".equals(IsReturned)) {//1设备已退货、0设备未退货
                        returnedDevices.add(returnDevice.getDeviceMac());
                    }
                }
            }
            //2.判断箱子是否已存在
            //如果从数据库中查询该箱子号的箱子标识为全部退货，则提示箱子已退货
            List<String> returnedBoxes = new ArrayList<>();
            if (returnRecordDTO.getReturnBoxList() != null && !returnRecordDTO.getReturnBoxList().isEmpty()) {
                for (ReturnRecordDTO.ReturnBox returnBox : returnRecordDTO.getReturnBoxList()) {
                    String boxFlag = returnPersonMapper.selectBoxFlag(returnBox.getBoxNumber());
                    if ("1".equals(boxFlag)) {//0代表箱子未退货、1箱子整箱退货、2代表箱子部分退货
                        returnedBoxes.add(returnBox.getBoxNumber());
                    }
                }
            }
            // 3. 如果有验证错误，返回错误结果
            if (!returnedDevices.isEmpty() || !returnedBoxes.isEmpty()) {
                StringBuilder errorMsg = new StringBuilder("退货失败: ");

                if (!returnedDevices.isEmpty()) {
                    errorMsg.append("以下设备已退货: ").append(String.join(", ", returnedDevices));
                    log.error(String.valueOf(errorMsg));
                }

                if (!returnedBoxes.isEmpty()) {
                    if (!returnedDevices.isEmpty()) errorMsg.append("; ");
                    errorMsg.append("以下箱子已退货: ").append(String.join(", ", returnedBoxes));
                    log.error(String.valueOf(errorMsg));
                }

                return Result.error(errorMsg.toString());
            }
            //4.保存退货记录
            ReturnRecord record = new ReturnRecord();
            //退货人
            record.setReturnPerson(returnRecordDTO.getReturnPerson());
            //退货时间
            record.setReturnTime(LocalDateTime.now());
            //退货数量
            record.setReturnCount(returnRecordDTO.getReturnCount());
            //退货类型
            record.setReturnType(returnRecordDTO.getReturnType());
            returnPersonMapper.addReturn(record);
            //5.处理设备信息

            if (returnRecordDTO.getReturnDeciceList() != null && !returnRecordDTO.getReturnDeciceList().isEmpty()) {
                // 5.1 收集所有设备号
                List<String> deviceMacs = returnRecordDTO.getReturnDeciceList().stream()
                        .map(ReturnRecordDTO.ReturnDevice::getDeviceMac)
                        .collect(Collectors.toList());
                // 5.2 查询deviceMacs中设备对应的箱码
                //创建设备到箱码的映射
                Map<String, String> deviceToBoxMap = new HashMap<>();
                for(String deviceMac : deviceMacs){
                    String boxNumber = returnPersonMapper.selectBoxNumberByDeviceMac(deviceMac);
                    if (boxNumber != null) {
                        deviceToBoxMap.put(deviceMac, boxNumber);
                    }
                }
                // 5.3 按箱码分组统计退货设备数量
                Map<String, Long> returnCountByBox = new HashMap<>();
                for (ReturnRecordDTO.ReturnDevice device : returnRecordDTO.getReturnDeciceList()) {
                    String boxNumber = deviceToBoxMap.get(device.getDeviceMac());
                    if (boxNumber != null) {
                        returnCountByBox.put(boxNumber, returnCountByBox.getOrDefault(boxNumber, 0L) + 1);
                    }
                }
                // 5.4 处理每个箱子的退货状态
                for (Map.Entry<String, Long> entry : returnCountByBox.entrySet()) {
                    String boxNumber = entry.getKey();
                    Long returnCount = entry.getValue();

                    // 查询箱子的总设备数
                    Integer totalCount = returnPersonMapper.selectTotalDeviceCountByBoxNumber(boxNumber);
                    if (totalCount != null) {
                        // 判断退货类型
                        String flag = returnCount.equals(totalCount.longValue()) ? "1" : "2"; // 1:整箱退货, 2:部分退货
                        // 更新箱子状态
                        Box returnBoxFlag = new Box();
                        returnBoxFlag.setBoxFlag(flag);
                        returnBoxFlag.setBoxNumber(boxNumber);
                        returnBoxFlag.setCreateTime(LocalDateTime.now());
                        returnPersonMapper.updateBox(returnBoxFlag);
                        log.info("箱子标识修改成功");
                    }
                }
                // 5.5 更新设备退货信息
                for (ReturnRecordDTO.ReturnDevice returnDev : returnRecordDTO.getReturnDeciceList()) {
                    Device returnDevice = new Device();
                    returnDevice.setReturnPerson(returnRecordDTO.getReturnPerson());
                    returnDevice.setDeviceMac(returnDev.getDeviceMac());
                    returnDevice.setCreateTime(LocalDateTime.now());
                    returnPersonMapper.updateDevice(returnDevice);
                }
            }

            //6.处理箱子信息
            if (returnRecordDTO.getReturnBoxList() != null && !returnRecordDTO.getReturnBoxList().isEmpty()) {
                for (ReturnRecordDTO.ReturnBox returnBox : returnRecordDTO.getReturnBoxList()) {
                    Device returnDevice = new Device();
                    //在设备表中插入退货人信息
                    returnDevice.setReturnPerson(returnRecordDTO.getReturnPerson());
                    returnDevice.setBoxNumber(returnBox.getBoxNumber());
                    returnDevice.setCreateTime(LocalDateTime.now());
                    returnPersonMapper.updateDevice(returnDevice);
                    //在箱子表中更新箱子状态
                    Box returnBoxFlag = new Box();
                    returnBoxFlag.setBoxFlag("1");
                    returnBoxFlag.setBoxNumber(returnBox.getBoxNumber());
                    returnBoxFlag.setCreateTime(LocalDateTime.now());
                    returnPersonMapper.updateBox(returnBoxFlag);
                }
            }
            log.info("设备退货成功");
            return Result.success("设备退货成功");
        } catch (Exception e) {
            throw new RuntimeException("设备退货失败,事务回滚", e);
        }
    }
}